<template>
  <div>
    <el-drawer class="dia-style" :title="title" :visible.sync="isOpen" width="60%" :close-on-click-modal="false" size="50%" :wrapper-closable="false" @close="cancel">
      <el-col :span="24">
        <div class="tips">基础信息</div>
      </el-col>
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="140px" @submit.native.prevent>
        <el-form-item label="数据源名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入数据源名称" maxlength="40" />
        </el-form-item>
        <el-form-item class="el-custom-item" label="数据源类型" prop="sourceType">
          <div v-for="(item,index) in dataType" :key="index" class="card-container" :class="{ active: formData.sourceType == item.keyValue}" @click="handleChangeDataType(item.keyValue)">
            <div class="card-pic">
              <img
                style="width: 26px; height:26px;vertical-align:middle"
                :src="item.iconUrl || require('@/assets/images/sjjr_jrsjy_01.png')"
                alt=""
              >
            </div>
            <div class="card-text hk-flex">
              <p class="card-title">{{ item.name }}</p>
            </div>
            <label v-if="formData.sourceType == item.keyValue" class="el-form-list__item-status-label"><i class="el-icon-upload-success el-icon-check" /></label>
          </div>
        </el-form-item>
        <!--  是否是JDBC类型 -->
        <template v-if="dataSourceType=='JDBC'">
          <el-col :span="12">
            <el-form-item label="数据库类型" prop="databaseTypeId">
              <el-cascader
                v-model="formData.databaseTypeId"
                :append-to-body="false"
                :options="databaseTypeOption"
                filterable
                :props="{ expandTrigger: 'hover' }"
                :style="{ width: '100%' }"
                placeholder="请选择数据库类型"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据库名称" prop="databaseName">
              <el-input
                v-model="formData.databaseName"
                placeholder="请输入数据库名称"
                maxlength="40"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="编码格式" prop="decoding">
              <div class="btn-wk">
                <el-button v-for="(i,index) in wayData" :key="index" :class="[activedDecoding==i.field?'active-btn':'','custom-btn']" @click="hancdleChangeWay(i.field)">{{ i.field }}</el-button>
              </div>
            </el-form-item>
          </el-col></template>
        <!--  是否是ES类型 -->
        <template v-if="dataSourceType=='ES'">
          <el-col :span="24">
            <el-form-item label="协议类型" prop="protocol" placeholder="请选择协议类型">
              <el-select v-model="formData.protocol" filterable>
                <el-option value="http">http</el-option>
                <el-option value="https">https</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </template>

        <!--  是否是Kafka类型 -->
        <template v-if="dataSourceType=='Kafka'">
          <el-col :span="24">
            <el-form-item label="主题名" prop="topic">
              <el-input v-model="formData.topic" placeholder="请输入主题名" maxlength="40" />
            </el-form-item>
          </el-col>
        </template>

        <el-col :span="24">
          <div class="tips">配置信息</div>
        </el-col>
        <!--    消息队列 Kafka     -->
        <template v-if="dataSourceType == 'Kafka'">
          <el-col :span="12">
            <el-form-item label="服务IP" prop="ip">
              <el-input v-model="formData.ip" placeholder="请输入Kafka服务IP" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务端口" prop="port">
              <el-input v-model="formData.port" placeholder="请输入服务端口" maxlength="5" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Kafka用户名" prop="username">
              <el-input
                v-model="formData.username"
                placeholder="请输入Kafka用户名"
                maxlength="40"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Kafka密码" prop="password">
              <el-input
                v-model="formData.password"
                maxlength="40"
                type="password"
                placeholder="请输入Kafka密码"
              />
            </el-form-item>
          </el-col>
        </template>
        <!--    ES      -->
        <template v-if="dataSourceType == 'ES'">
          <el-col :span="12">
            <el-form-item label="ES服务IP" prop="ip">
              <el-input v-model="formData.ip" placeholder="请输入ES服务IP" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ES服务端口" prop="port">
              <el-input
                v-model="formData.port"
                placeholder="请输入ES服务端口"
                maxlength="5"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ES用户名" prop="username">
              <el-input
                v-model="formData.username"
                placeholder="请输入ES用户名"
                maxlength="40"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ES密码" prop="password">
              <el-input
                v-model="formData.password"
                type="password"
                placeholder="请输入ES密码"
                maxlength="40"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="索引名称" prop="indexName">
              <el-input
                v-model="formData.indexName"
                placeholder="请输入索引名称"
                maxlength="40"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="元数据" prop="metaId">
              <el-select v-model="formData.metaId" filterable style="width: 100%">
                <el-option
                  v-for="item in yuanData"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </template>
        <!--     数据库     -->
        <template v-if="dataSourceType == 'JDBC'">

          <el-col :span="12">
            <el-form-item label="数据库IP" prop="ip">
              <el-input v-model="formData.ip" placeholder="请输入数据库IP" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据库端口" prop="port">
              <el-input v-model="formData.port" placeholder="请输入数据库端口" maxlength="5" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据库用户名" prop="username">
              <el-input
                v-model="formData.username"
                placeholder="请输入数据库用户名"
                maxlength="40"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据库密码" prop="password">
              <el-input
                v-model="formData.password"
                placeholder="请输入数据库密码"
                type="password"
                maxlength="40"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据库表名称" prop="tableName">
              <el-input
                v-model="formData.tableName"
                placeholder="请输入数据表名称"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="元数据" prop="metaId">
              <el-select v-model="formData.metaId" style="width: 100%" placeholder="请选择元数据">
                <el-option
                  v-for="item in yuanData"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </template>

      </el-form>
      <div class="el-drawer-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { dataBaseList } from '@/api/milkyway/gatherData'
import { getPostsource, getMetaType, updateSource, addSource } from '@/api/milkyway/repositorypage'

export default {
  props: {
    title: {
      type: String,
      default() {
        return '编辑'
      }
    },
    dataType: {
      type: Array,
      default() {
        return []
      }
    },
    sourceType: {
      type: String,
      default() {
        return 'JDBC'
      }
    }
  },
  data() {
    return {
      yuanData: [],
      activedDecoding: 'UTF-8',
      // 数据库选择下拉框
      databaseTypeOption: [],
      // http请求
      protocolOptions: [
        { label: 'http', value: 'http' },
        { label: 'https', value: 'https' }
      ],
      propsData: { value: 'id', label: 'dataName', multiple: false },
      hidden: true,
      isOpen: false,
      showAddDialog: false,
      showSelectDialog: false,
      checkNodes: [],
      formData: {
        databaseTypeId: '',
        databaseName: '',
        connectInfo: {},
        decoding: 'UTF-8',
        sourceType: this.sourceType
      },
      // 表单参数
      rules: {
        name: [{ required: true, message: '数据源名称不能为空', trigger: 'blur' }],
        decoding: [{ required: true, message: '请选择编码格式', trigger: 'blur' }],
        sourceType: [{ required: true, message: '请选择数据源类型', trigger: 'blur' }],
        protocol: [{ required: true, message: '请选择协议类型', trigger: 'blur' }],
        indexName: [{ required: true, message: '请输入索引名称', trigger: 'blur' }],
        sendIp: [
          { required: true, message: '请输入发送端IP', trigger: 'blur' },
          {
            pattern:
              /^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))$/,
            message: '请输入正确的IP地址',
            trigger: 'blur'
          }
        ],
        serveIP: [
          { required: true, message: '请输入服务端IP', trigger: 'blur' },
          {
            pattern:
              /^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))$/,
            message: '请输入正确的IP地址',
            trigger: 'blur'
          }
        ],
        ip: [
          { required: true, message: '请输入服务IP', trigger: 'blur' },
          {
            pattern:
              /^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))$/,
            message: '请输入正确的IP地址',
            trigger: 'blur'
          }
        ],
        port: [
          { required: true, message: '请输入端口号', trigger: 'blur' },
          {
            pattern: /^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{4}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/,
            message: '请输入正确的端口号',
            trigger: 'blur'
          }
        ],
        'topic': [{ required: true, message: '请输入主题名', trigger: 'blur' }],
        'groupId': [{ required: true, message: '请输入消费组Id', trigger: 'blur' }],
        'tableName': [{ required: true, message: '请输入数据库表名称', trigger: 'blur' }],
        'metaId': [{ required: true, message: '请选择元数据', trigger: 'blur' }]
      },
      dataSourceType: this.sourceType || 'JDBC',
      wayData: [
        { field: 'UTF-8' },
        { field: 'GBK' },
        { field: 'UTF-16' }
      ]
    }
  },
  watch: {
  },
  created() {
    this.dataBaseList()
  },
  methods: {
    /** 显示弹窗*/
    show(id) {
      this.isOpen = true
      getMetaType().then((res) => {
        this.yuanData = res.map(item => {
          return {
            label: item.mdName,
            value: item.id
          }
        })
      })
      if (id) {
        getPostsource({ id: id }).then((res) => {
          this.formData = JSON.parse(JSON.stringify(this.getDetails(res)))
          this.dataSourceType = this.formData.sourceType
          this.activedDecoding = this.formData?.decoding || 'UTF-8'
        })
      } else {
        this.formData.sourceType = this.sourceType || 'JDBC'
        this.formData.decoding = 'UTF-8'
        this.dataSourceType = this.sourceType || 'JDBC'
      }
    },
    getDetails(res) {
      const _res = res
      if (Array.isArray(res)) {
        _res.forEach((item) => {
          const _data = JSON.parse(item.connectInfo)
          item.databaseTypeId = _data.databaseTypeId || undefined
          item.databaseName = _data.databaseName || undefined
          item.tableName = _data.tableName || undefined
          item.topic = _data.topic || undefined
          item.groupId = _data.groupId || undefined
          item.protocol = _data.protocol || undefined
          item.indexName = _data.indexName || undefined
          item.metaName = item.jsonObject.metaName || undefined
          item.metaId = item.jsonObject.metaId
          item.taskNums = item.jsonObject.taskNums || undefined
          item.tasks = item.jsonObject.tasks || undefined
        })
      } else {
        const data = JSON.parse(_res.connectInfo)
        _res.databaseTypeId = data.databaseTypeId || undefined
        _res.databaseName = data.databaseName || undefined
        _res.tableName = data.tableName || undefined
        _res.topic = data.topic || undefined
        _res.groupId = data.groupId || undefined
        _res.protocol = data.protocol || undefined
        _res.indexName = data.indexName || undefined
      }
      return _res
    },
    reset() {
      this.resetForm('formRef')
    },
    /** 获取数据库列表 */
    dataBaseList() {
      dataBaseList().then((res) => {
        this.databaseTypeOption = res.map(item => {
          return {
            value: item.id,
            label: item.dataName
            // children: this.getDatabase(item.children)
          }
        })
      })
    },
    // 获取数据库
    getDatabase(item, index) {
      if (item) {
        return item.map((i, index) => {
          return {
            value: i.id,
            label: i.dataName
          }
        })
      } else {
        return
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          if (this.formData.sourceType == 'JDBC') {
            this.formData.connectInfo = `{"databaseTypeId": "${
              this.formData.databaseTypeId || ''
            }","databaseName": "${this.formData.databaseName || ''}","tableName": "${
              this.formData.tableName || ''
            }"}`
          } else if (this.formData.sourceType == 'Kafka') {
            this.formData.connectInfo = `{"topic": "${this.formData.topic || ''}","groupId": ""}`
          } else if (this.formData.sourceType == 'ES') {
            this.formData.connectInfo = `{"protocol": "${this.formData.protocol || ''}","indexName": "${this.formData.indexName || ''}"}`
          }
          if (this.title === '编辑') {
            updateSource({
              metaId: this.formData.metaId,
              dataSource: this.formData
            }).then((res) => {
              this.$modal.msgSuccess('修改成功')
              this.isOpen = false
              this.$emit('changeOpen', false)
            })
          } else {
            addSource({
              metaId: this.formData.metaId,
              dataSource: this.formData
            }).then((res) => {
              this.$modal.msgSuccess('新增成功')
              this.isOpen = false
              this.$emit('changeOpen', false)
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.importProduct = []
      this.formData = {}
      this.activedDecoding = 'UTF-8'
      this.$refs.formRef.clearValidate()
      this.isOpen = false
    },

    /** 关闭弹窗*/
    dialogSubmitEvent(data) {
      this.importProduct = data
    },
    /** 切换数据源类型 */
    handleChangeDataType(key) {
      this.$nextTick(() => {
        this.formData.sourceType = key
        this.$refs.formRef.clearValidate()
      })

      this.dataSourceType = key
    },
    /** 切换编码格式按钮 */
    hancdleChangeWay(key) {
      this.$nextTick(() => {
        this.activedDecoding = key
        this.formData.decoding = this.activedDecoding
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-cascader-menu__wrap{
  height:100% !important;
}
.card-container{
  margin-right:20px;
  margin-bottom:10px;
}
.active {
  border-color: #2979ff;
  // background: #e4eeff;
}
::v-deep .el-table__body-wrapper {
  height: 200px !important;
  overflow-y: auto !important;
}
.el-cascader {
  width: 100%;
}
.el-form-item__label {
  width: 140px !important;
}

.el-form-item__content {
  margin-left: 140px !important;
}
</style>
